package com.project.queue.tool;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author mengxj
 */
@Component
public class RabbitMqQueue extends BaseQueue {

    private static RabbitMqQueue instance;

    @Resource
    public void setRabbitMqQueue(RabbitMqQueue rabbitMqQueue) {
        RabbitMqQueue.instance = rabbitMqQueue;
    }

    public static RabbitMqQueue getInstance(){
        return instance;
    }

    @Resource
    private RabbitTemplate rabbitTemplate;

    public void pushObject(String exchange, String json){
        this.pushObject(exchange, null, json, null);
    }

    public void pushObject(String exchange, String routingKey, String json, String id){
        if(Objects.nonNull(id)){
            this.rabbitTemplate.convertAndSend(exchange, json);
        }else{
            CorrelationData data = new CorrelationData();
            data.setId(String.format("%s %s %s", id, exchange, routingKey));
            this.rabbitTemplate.convertAndSend(exchange, routingKey, json, data);
        }
    }

    @Override
    public void send(String queue, String value) {
        this.pushObject(queue, value);
    }
}
